<?php

namespace App\Logic\Dashboard;

use App\Component\User;
use App\Component\LogListForm;
use App\Core\BaseCore;
use App\Core\BaseModel;
use App\Core\Exception\DefaultException;
use App\Core\Exception\ValidationException;
use App\Core\Output;
use App\Enums\ValidateEnums;
use App\Event\Event;
use App\Logic\Dashboard\Form\DashboardStatisticsForm;
use App\Model\Member\MemberModel;
use App\Model\UserModel;
use App\Util\ArrayHelper;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Component\Di;
use EasySwoole\Component\Singleton;
use EasySwoole\EasySwoole\Config as ESConfig;
use EasySwoole\Http\Request;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Redis\Redis;
use EasySwoole\RedisPool\RedisPool;
use EasySwoole\Utility\Random;
use EasySwoole\Validate\Validate;
use Throwable;

class DashboardService extends BaseCore
{

    use Singleton;

    /**
     * 数据统计 statistics
     * @param Request $request
     * @return Output
     * @throws Throwable
     * @throws \EasySwoole\Redis\Exception\RedisException
     */
    public function statistics(Request $request):Output
    {
        $params = $request->getQueryParams();
        /** @var Redis $cache */
        $cache     = Di::getInstance()->get("REDIS");
        $cache_key = "dashboardCache:list:" . json_encode($params + ['_id' => UserIdentityHelper::getId(), '_name' => UserIdentityHelper::getUsername()]);
        if ($cache_data = $cache->get($cache_key)) { //缓存存在
            $data = json_decode($cache_data, true);
        } else {
            if (UserIdentityHelper::getType() == UserModel::TYPE_INSIDE) {
                $data = [];
            }
            else {
                $form = new DashboardStatisticsForm($params, $request);
                $data = $form->statistics();
                $cache->set($cache_key, json_encode($data), BaseModel::CACHE_EXPIRE / 10);
            }
        }
        return $this->success($data);
    }

}
